import axios from 'axios'
import { getToken } from '@/utils/storage'
import router from '@/router'
import { Message } from 'element-ui'

const instance = axios.create({
    baseURL: 'https://slwl-api.itheima.net/',
    timeout: 5000
})

// 添加请求拦截器
instance.interceptors.request.use(function(config) {
    config.headers.Authorization = getToken()
    return config
}, function(error) {
    return Promise.reject(error)
})

// 添加响应拦截器
instance.interceptors.response.use(function(response) {
    if (response.data.msg) {
        if (response.data.code === 1) Message.error(response.data.msg)
        if (response.config.url === '/manager/login' && response.data.code === 200) Message.success('登录成功')
    }
    return response
}, function(error) {
    if (error.response && error.response.status === 401) {
        Message.error('请重新登录')
        router.push('/login')
    } else if (!error.response) {
        Message.error('服务器或网络异常，请稍后再试')
    } else if (error.response.status === 500) {
        Message.error('当前状态异常，请稍后再试')
    }

    return Promise.reject(error)
})

export default instance
